<template>
    <div>
        <el-dialog title="新建页面" :visible.sync="dialogVisible" :modal-append-to-body="false" :close-on-click-modal="false" width="40%" class="newspage" :before-close="handleClose">
            <el-form label-width="120px" label-position="right" style="width:85%;">
                <el-form-item label="标题：">
                    <el-input type="text" size="small" v-model="page.title" placeholder="请输入标题"></el-input>
                </el-form-item>
                <el-form-item label="名称：">
                    <span class="_tips">格式：名称只能包含大小写字母，数字。例：addGoods。</span>
                    <el-input type="text" size="small" v-model="page.name" placeholder="请输入名称"></el-input>
                </el-form-item>
                <el-form-item label="宽度：">
                    <el-input-number type="text" :min="0" size="small" v-model="page.width"></el-input-number> px
                </el-form-item>
                <el-form-item label="高度：">
                    <el-input-number type="text" :min="0" size="small" v-model="page.height"></el-input-number> px
                </el-form-item>
                <el-form-item label="选择页面组：" class="_boxGroups">
                    <span class="_boxGroups-item">{{ page.path }}</span>
                    <div class="_group-maxhight">
                        <el-tree :data="path" :props="defaultProps" node-key="path" @node-click="handleNodeClick">
                            <span class="_tree-node" slot-scope="{node,data}">
                                <span>{{ node.label }}</span>
                                <span class="_tree-node-action">
                                    <i class="el-icon-plus" @click="() => append(data)" v-if="data.path === path[0].path"></i>
                                    <i class="el-icon-delete" @click="() => del(data)" v-else></i>
                                </span>
                            </span>
                        </el-tree>
                    </div>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="intCreate">创 建</el-button>
            </span>
        </el-dialog>
        <!-- 添加页面分组 -->
        <el-dialog :visible.sync="addPageGroupWin" title="添加页面组" width="22%" class="newspage-add-group" :modal-append-to-body='false' :close-on-click-modal="false" :before-close="handleCloseGroupWin">
            <span class="_tips">格式：只能包含英文字母（例：goods）</span>
            <span class="_content">
                <el-input v-model="pathName" type="text" size="mini" />
                <el-button @click="intAddGroup" type="primary" size="mini">添加</el-button>
            </span>
            <span slot="footer">
            </span>
        </el-dialog>
    </div>
</template>
<script type="text/javascript">
//通过命名空间的方式映入
import { createNamespacedHelpers } from 'vuex'
//获取需要管理的方法
const { mapState, mapActions, mapGetters, mapMutations } = createNamespacedHelpers('cloud')

import canvas from '../../widgets/basics/canvas/index.js'

export default {
    props: {
        value: [Object, Array, String, Number, Boolean]
    },
    components: {
        //empty
    },
    data() {
        return {
            model_config: canvas,
            addPageGroupWin: false,
            dialogVisible: false,
            defaultProps: {
                children: 'children',
                label: 'path'
            },
            page: {
                title: "",
                type: "page",
                name: "",
                width: 800,
                height: 500,
                path: "",
            },

            pathName: '',
            path: [{
                path: '页面组',
                disabled: true,
                children: []
            }],
        }
    },
    /**
     * 计算属性
     * @type {Object}
     */
    computed: {

    },
    /**
     * 数据监听
     * @type {Object}
     */
    watch: {

    },
    /**
     * 页面加载执行
     * @return {[type]} [description]
     */
    mounted() {
        this.getGroupAll();
    },
    /**
     * 页面方法
     * @type {Object}
     */
    methods: {
        ...mapActions(['setPage']),
        handleClose() {
            this.dialogVisible = false;
        },
        handleCloseGroupWin() {
            this.addPageGroupWin = false;
        },

        //添加页面组
        append(data) {
            this.pathName = '';
            this.addPageGroupWin = true;
            // 处理冒泡
            event.cancelBubble = true;
            event.stopPropagation();
        },

        //添加页面组
        intAddGroup() {
            let reg = /^[a-zA-Z][a-zA-Z0-9]+$/;
            if (reg.test(this.pathName)) {
                this.$cloud.post("build/page_group_add", { path: this.pathName }).then(response => {
                    this.page.path = this.pathName;
                    this.$message.success('添加页面分组成功！');
                    this.addPageGroupWin = false;
                    this.getGroupAll();
                })
            } else {
                this.$message({
                    message: '输入格式不合法，请重新输入！',
                    type: 'warning'
                });
            }
        },

        //删除页面组
        del(data) {
            this.$confirm('页面分组删除后将不可恢复, 是否继续?', '提示', {
                confirmButtonText: '继续',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$cloud.post('build/page_group_del', { path: data.path }).then(response => {
                    this.path[0].children.forEach((item, index) => {
                        if (item.path == data.path) {
                            this.page.path = this.page.path === data.path ? "" : this.page.path;
                            this.path[0].children.splice(index, 1);
                            this.$message.success('删除成功！');
                        }
                    })
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
            // 处理冒泡
            event.cancelBubble = true;
            event.stopPropagation();
        },

        /**
         * 获取所有分组
         * @return {[type]} [description]
         */
        getGroupAll() {
            this.$cloud.get('build/page_group_all').then(response => {
                console.log('response', response);
                this.path[0].children = [];
                response.forEach(item => {
                    this.path[0].children.push({ path: item })
                })
            })
        },

        /**
         * 选中树状页面组
         * @param  {[type]} data [description]
         * @return {[type]}      [description]
         */
        handleNodeClick(data) {
            if (data.path != this.path[0].path) {
                this.page.path = data.path
            }
        },


        /**
         * 创建页面
         * @return {[type]} [description]
         */
        intCreate() {
            //判断规则
            if (!this.checked()) {
                return false;
            }

            this.page.width = this.page.width + 'px';
            this.page.height = this.page.height + 'px';

            //提交
            this.model_config.data = this.page;

            this.setPage(this.model_config);

            this.dialogVisible = false;
        },


        /**
         * 检查输入是否合法
         * @return {[type]} [description]
         */
        checked() {
            let ret = false;
            let tips = '';
            let rules = /^[a-zA-Z][a-zA-Z0-9]+$/;
            if (!this.page.title) {
                tips = '请输入标题！';
                ret = true;
            } else if (this.page.name == 'index' || !rules.test(this.page.name)) {
                tips = '输入的名称不符合规则！';
                ret = true;
            } else if (!(this.page.width > 0 && this.page.height > 0)) {
                tips = "请输入有效的宽高值！";
                ret = true;
            } else if (!this.page.path) {
                tips = '请选择页面分组！';
                ret = true;
            } else if (rules.test(this.page.name)) {
                /**
                 * 检测输入name是否重复
                 * @return {[type]} [description]
                 */
                this.$cloud.post('build/page_check', { name: this.page.name, path: this.page.path }).then(response => {
                    if (response.code != 0) {
                        tips = '该名称已被占用';
                        ret = true;
                    }
                });
            }

            if (ret) {
                this.$message.warning(tips);
            }
            return !ret;
        }


    }
}
</script>
<style type="text/css" lang="scss">
.newspage {
    .el-dialog {
        min-width: 555px;
    }

    ._tips {
        color: red;
        font-size: 12px;
        display: block;
        height: 24px;
    }

    .el-form-item {
        margin-bottom: 5px;
    }

    ._boxGroups {
        .el-form-item__content {
            margin-top: 5px;
            line-height: 0px !important;
        }

        ._group-maxhight {
            overflow-y: auto;
            max-height: 120px;
            border: solid 1px #DCDFE6;
            border-top: none;
        }

        ._boxGroups-item {
            width: calc(100% - 32px);
            height: 34px;
            padding: 0 15px;
            line-height: 34px;
            display: inline-block;
            border: solid 1px #DCDFE6;
            border-radius: 2px;
        }
    }

    ._tree-node {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 14px;
        padding-right: 8px;

        ._tree-node-action {
            text-align: right;
        }
    }
}

.newspage-add-group {
    ._content {
        display: flex;
        align-items: center;
        justify-content: flex-start;
    }

    ._tips {
        color: red;
        font-size: 12px;
        line-height: 24px;
    }

    .el-button--mini,
    .el-input__inner,
    .el-button {
        border-radius: 0px;
    }

    .el-dialog__body {
        padding-top: 0px;
    }

    .el-dialog__footer {
        padding: 0px;
        margin: 0px;
    }
}
</style>